package lzupdater.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.Vector;

import lzupdater.log.Logger;
import lzupdater.log.LoggerLevel;

//LZRosterUpdater, a java client to update LZRoster
//Copyright (C) 2008 Fraskor from Krasus (e-mail: fraskor@gmail.com)
//
//This file is part of LZRosterUpdater.
//
//LZRosterUpdater is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with this program.  If not, see <http://www.gnu.org/licenses/>.

/**
 * 
 * @author Fraskor
 */
public class Text implements Iterable<String> {

	private Vector<String> lines;

	public Text(InputStream is) throws IOException {
		lines = new Vector<String>();

		BufferedReader b = new BufferedReader(new InputStreamReader(is));
		String line = null;
		while ((line = b.readLine()) != null) {
			lines.add(line);
		}
		b.close();
	}

	/**
	 * Verify if the current Text contains a specific string
	 * 
	 * @param textToFind
	 * @return the line number at which the textToFind has been found, -1 if no
	 *         line matches the search.
	 */
	public int contains(String textToFind) {
		boolean found = false;
		int lineNumber;

		for (lineNumber = 0; lineNumber < lines.size(); lineNumber++) {
			if ((found = lines.get(lineNumber).contains(textToFind))) {
				break;
			}
		}

		return found ? lineNumber : -1;
	}

	public void display() {
		display(System.out);
	}

	public void display(PrintStream stream) {
		stream.println(this);
	}

	public String getLine(int lineNumber) {
		if (lineNumber < 0 || lineNumber >= lines.size())
			return "";
		return lines.get(lineNumber);
	}

	public int getNumberOfLines() {
		return lines.size();
	}

	@Override
	public String toString() {
		if (lines.isEmpty())
			return "";

		StringBuffer resultat = new StringBuffer();
		int size = lines.size();
		int nbDigits = (int) Math.floor(1 + Math.log10(size));
		String format = String.format("%%0%dd : %%s", nbDigits);
		for (int i = 0; i < size; i++) {
			resultat.append(String.format(format, i + 1, lines.get(i)));
			if (i != (size - 1)) {
				resultat.append("\n");
			}
		}
		return resultat.toString();
	}

	public Iterator<String> iterator() {
		return lines.iterator();
	}

	public void dump(Logger log, LoggerLevel level) {
		for (String s : this) {
			log.write(s, level);
		}
	}

}
